package com.thinklib.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.thinklib.bean.Book;
import com.thinklib.bean.ExtCode;
import com.thinklib.mapper.SearchMapper;
import com.thinklib.service.SearchService;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.*;

@Service
public class SearchServiceImpl implements SearchService {

    @Resource
    private SearchMapper searchMapper;

    // 公共线程池
    public static ExecutorService executorService = Executors.newFixedThreadPool(16, new BasicThreadFactory.Builder().namingPattern("ThreadPool-SearchBook-%d").daemon(true).build());

    @Override
    public List<Book> findBookByBookName(String bookName) {
        List<Book> bookList = searchMapper.search(bookName);
        return bookList;
    }

    @Override
    public PageInfo<Book> searchBookThread(HttpServletRequest request) {
        PageInfo<Book> pageInfo = null;
        Callable<PageInfo<Book>> task = () -> {
            String keywords = request.getParameter("keywords");
            Integer pageSize = Integer.valueOf(request.getParameter("pageSize").toString());
            Integer pageNum = Integer.valueOf(request.getParameter("pageNum").toString());

            // 分页查询
            PageHelper.startPage(pageNum, pageSize);
            List<Book> bookList = searchMapper.search(keywords);
            PageInfo<Book> pageInfo1 = new PageInfo<Book>(bookList);
            return pageInfo1;
        };
        Future<PageInfo<Book>> future = executorService.submit(task);
        try {
            pageInfo = future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return pageInfo;
    }

    @Override
    public ExtCode findExtCodeByBookId(int bookId) {
        ExtCode extCode = searchMapper.findExtCodeByBookId(bookId);
        extCode.setBookId(bookId);
        return extCode;
    }
}
